﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;

namespace PlanetWPF.Toolbelt.Utils
{
    public class GridViewHelper
    {
        #region MaxColumnWidth (Attached Property)

        public static readonly DependencyProperty MaxColumnWidthProperty =
            DependencyProperty.RegisterAttached("MaxColumnWidth", typeof(Double), typeof(GridViewHelper),
                new FrameworkPropertyMetadata(Double.NaN, new PropertyChangedCallback(OnMaxColumnWidthChanged)));

        public static Double GetMaxColumnWidth(DependencyObject d)
        {
            return (Double)d.GetValue(MaxColumnWidthProperty);
        }

        public static void SetMaxColumnWidth(DependencyObject d, Double value)
        {
            d.SetValue(MaxColumnWidthProperty, value);
        }

        private static void OnMaxColumnWidthChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            Double newVal = (Double)args.NewValue;

            if (newVal != Double.NaN && newVal > 0)
            {
                GridViewColumn column = sender as GridViewColumn;
                if (column != null)
                {
                    column.Width = Math.Min(column.Width, newVal);
                    ((INotifyPropertyChanged)column).PropertyChanged += new PropertyChangedEventHandler(WidthChanged);
                        
                }
            }
        }

        static void WidthChanged(object sender, PropertyChangedEventArgs e)
        {
            GridViewColumn column = sender as GridViewColumn;
            if (e.PropertyName == "Width")
            {
                Double maxWidth = GetMaxColumnWidth(column);
                if (maxWidth != Double.NaN)
                {
                    ((INotifyPropertyChanged)column).PropertyChanged -= new PropertyChangedEventHandler(WidthChanged);
                    column.Width = Math.Min(column.Width, maxWidth);
                    ((INotifyPropertyChanged)column).PropertyChanged += new PropertyChangedEventHandler(WidthChanged);
                }
            }
        }


        #endregion


    }
}
